Note: This Java deployment guide describes features released prior to the Java SE 6 update 10 release. See Java Rich Internet Applications Development and Deployment for the latest information.
When running an applet in a browser using the Sun
Java™ Runtime Environment (JRE™), deadlock may occur
if methods of the applet are over-synchronized, especially
those inherited from java.awt.Component
. The same
applet runs under the Microsoft Virtual Machine (VM).
The AWT class libraries are sometimes used by developers as
thread-safe class libraries. Applets performed actions through the
AWT using multiple threads, with the assumption that the class
libraries would take care of synchronization issues.
However , the AWT class libraries guarantee thread safety only when
calls are made from the AWT event dispatch thread. Because the
implementation of the Microsoft VM and Sun differs, thread-unsafe
code that runs without incident under one VM might fail under
another.
One bad practice used by some applets is to synchronize every method of an applet to avoid possible race conditions or deadlocks in the Microsoft VM. However, this practice may result in deadlocks.
To work around this problem, use synchronization in the applet only where it is really needed, and remove unnecessary synchronization. For example:
public
synchronized void paint(Graphics g) {
....
}
public synchronized void dispose()
{
super.dispose();
.....
}
public synchronized void stop() {
....
}
public synchronized void destroy() {
....
}
In this case, the synchronized
keyword in the
paint
, dispose
, stop
, and
destroy
methods should be removed because they are
always called from a dedicated thread: paint
and
dispose
by the AWT event dispatching thread;
stop
and destroy
by the applet thread.
The code should be changed as follows:
public void
paint(Graphics g) {
....
}
public void dispose()
{
super.dispose();
.....
}
public void stop() {
....
}
public void destroy() {
....
}
The Java Tutorial discusses thread issues and techniques that apply both to AWT and Swing programs: Concurrency in Swing.